package cn.wit.summit.chwan.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.MobileCodeUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.RegularUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.SystemInfoUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import retrofit2.Retrofit;

/**
 * 登录页面
 */
public class MainLoginActivity extends MyActivity {

    @Bind(R.id.ed_iphone)
    EditText ed_iphone;
    @Bind(R.id.tv_Verification)
    TextView tv_Verification;
    @Bind(R.id.et_iphone_code)
    EditText ed_ipnone_code;
    @Bind(R.id.tv_showtime)
    TextView tv_showtime;
    @Bind(R.id.btn_login)
    Button btn_login;
    @Bind(R.id.btn_pwd_login)
    Button btn_login_Verification;

    int index = 60;
    boolean isLogon = true;
    private String NetCode;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            showSoftInput(ed_iphone);
        }
    };

    private RetrofitManager retrofitManager;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_login);
        ButterKnife.bind(this);
        setBarTitleTx(getString(R.string.btn_login_txt));
        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);
//        showSoftInput(ed_iphone);
       int ennergy= getIntent().getIntExtra("energyNumber",0);
        handler.sendEmptyMessageDelayed(1, 500);

        ed_iphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (i == 10) {
                    tv_Verification.setTextColor(getResources().getColor(R.color.color_txt_blue));
                    if (i1==1){
                        tv_Verification.setTextColor(getResources().getColor(R.color.home_gray));
                    }
                }else{
                    tv_Verification.setTextColor(getResources().getColor(R.color.home_gray));
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideSoftInput(ed_iphone);
        hideSoftInput(ed_ipnone_code);
    }

    @OnClick({R.id.tv_Verification, R.id.btn_pwd_login, R.id.btn_login})
    public void onViewOnclick(View view) {
        switch (view.getId()) {
            case R.id.tv_Verification:
                //获取验证码
                if (NetWorkUtils.isNetworkConnected(MainLoginActivity.this))
                    getVerification();
                else
                    ToastUtils.getInstance(MainLoginActivity.this).showToastSystem("网络连接失败，再试试吧~");
                break;
            case R.id.btn_login:
                //登录
                getLogin();


                break;
            case R.id.btn_pwd_login:
                //账户密码登录
                startActivity(new Intent(MainLoginActivity.this, AccountLoginActivity.class));
                finish();
                break;

        }
    }

    String shareCode = "";

    private void getLogin() {
        hideSoftInput(ed_iphone);
        hideSoftInput(ed_ipnone_code);
        String iphone = ed_iphone.getText().toString().trim();
        String code = ed_ipnone_code.getText().toString().trim();
        shareCode = getShareCodeByWalle(); // 注册邀请码 有就上传，没有就传空字符。
//        Toast.makeText(MainLoginActivity.this, "注册邀请码:"+shareCode, Toast.LENGTH_SHORT).show();
        if (NetWorkUtils.isNetworkConnected(MainLoginActivity.this)) {
            if (StringUtils.isNotEmpty(iphone) && StringUtils.isNotEmpty(code)) {
               String  imei = SystemInfoUtils.getInstance(this).getIMEI();
                if (StringUtils.isEmpty(imei)){
                    checkAllPerm();
                    return;
                }

                apiLogin.getCodeLogin(iphone, code, shareCode).enqueue(new MyCallback<ResponseBase<AccountBean>>() {
                    @Override
                    public void onSuccess(ResponseBase<AccountBean> model) {
                        AccountBean data = model.getData_info();
                        isLogon = true;
                        setSP(data);
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        isLogon = true;
                        Log.e("TAG", msg + "Code" + code);
                        Toast.makeText(MainLoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Toast.makeText(MainLoginActivity.this, "手机号或验证码为空", Toast.LENGTH_SHORT).show();
            }
        } else {
            ToastUtils.getInstance(MainLoginActivity.this).showToastSystem("网络连接失败，再试试吧~");
        }

    }

    private void setSP(AccountBean data) {

        LogUtils.e("codeToken:" + data.getToken());
        Log.e("TAG",data.getUid()+"|"+data.getToken());

        AccountUtil.getInstance().saveAccountData(data);
        hideSoftInput(ed_iphone);
        hideSoftInput(ed_ipnone_code);

        if (data.getDefaultNickname()==0 || data.getAvatar().contains("avatar_default")) {//未设置昵称
            Intent intent = new Intent(mContext, SetPersonalInformationActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("login_data", data);
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
            return;
        }

        Toast.makeText(MainLoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
        String gameid= PreferenceUtil.getPreferences(this,"toursEnergyPreGameID");
        if (StringUtils.isNotEmpty(gameid)){
            DownloadTool.sendMessageEnergy(this,gameid);
        }
        finish();
    }


    /**
     * 获取验证码
     * 正则验证
     */
    private void getVerification() {
        if (StringUtils.isNotEmpty(ed_iphone.getText().toString().trim())) {
            if (RegularUtil.getIphoneCorrect(ed_iphone.getText().toString().trim()) == true) {
                tv_Verification.setVisibility(View.GONE);
                tv_showtime.setVisibility(View.VISIBLE);
                index = 60;
                MobileCodeUtils.getCode(MainLoginActivity.this, ed_iphone.getText().toString().trim());
                tv_showtime.setText(60 + "s后重发");
                setLoadTime();
                ed_ipnone_code.setFocusable(true);
                ed_ipnone_code.setFocusableInTouchMode(true);
                ed_ipnone_code.requestFocus();
            } else {
                Toast.makeText(MainLoginActivity.this, "手机格式不正确", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(MainLoginActivity.this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
        }
    }


    private void setLoadTime() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                --index;
                tv_showtime.setText("" + index + "s后重发");
                if (index == 0) {
                    index = 60;
                    tv_showtime.setVisibility(View.GONE);
                    tv_Verification.setVisibility(View.VISIBLE);
                } else {
                    setLoadTime();
                }
            }
        }, 1000);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideSoftInput(ed_iphone);
        hideSoftInput(ed_ipnone_code);
//        ButterKnife.unbind(this);
    }
}
